package com.google.code.irouter.plugin.bot;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.Validate;
import org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.tags.InputTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.SimpleNodeIterator;

import weibo4j.Status;
import weibo4j.User;
import weibo4j.Weibo;
import weibo4j.WeiboException;
import weibo4j.http.AccessToken;
import weibo4j.http.PostParameter;
import weibo4j.http.RequestToken;

import com.google.code.irouter.batch.api.Bot;
import com.google.code.irouter.model.Human;

public final class SinaWeiboBot extends Bot {

	private static final long serialVersionUID = -4017818580054621121L;
	
	private Weibo weibo;
	private RequestToken requestToken;
	private String token;
	private String tokenSecret;
	
	private final String consumerKey = "4232662558";
	
	private final String consumerSecret = "42ea7c9b70d5e536c56aaa7e3b8aadb5";
	
	@Override
	protected List<Human> getList() {
		List<Human> result = new ArrayList<Human>();
		try {
			init(consumerKey, consumerSecret);			
			if(auth("tuandoudou@gmail.com", "983221")) {
				weibo.setToken(token, tokenSecret);
				List<Status> status = weibo.getPublicTimeline();
				for(Status statu : status) {
					Human people = new Human();
					User friend = statu.getUser();
					people.setType(SinaWeiboBot.class.getSimpleName());
					people.setId(String.valueOf(friend.getId()));
					people.setName(friend.getName());
					if("f".equals(friend.getGender())) {
						people.setGender(Human.FEMALE);
					} else {
						people.setGender(Human.MALE);
					}
					people.setProvince(friend.getProvince());
					people.setCity(friend.getCity());
					people.pushCreatDate();
					result.add(people);
				}
			}	
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	@Override
	protected List<Human> getList(String userId) {
		List<Human> result = new ArrayList<Human>();
		try {
			init(consumerKey, consumerSecret);		
			if(auth("tuandoudou@gmail.com", "983221")) {	
				weibo.setToken(token, tokenSecret);
				List<User> friends = weibo.getFriends(String.valueOf(userId));
				for(User friend : friends) {
					Human people = new Human();
					people.setType(SinaWeiboBot.class.getSimpleName());
					people.setId(String.valueOf(friend.getId()));
					people.setName(friend.getName());
					if("f".equals(friend.getGender())) {
						people.setGender(Human.FEMALE);
					} else {
						people.setGender(Human.MALE);
					}
					people.setProvince(friend.getProvince());
					people.setCity(friend.getCity());
					people.pushCreatDate();
					result.add(people);
				}
			}	
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
	private void init(String consumerKey, String consumerSecret) {
		System.setProperty("weibo4j.oauth.consumerKey", consumerKey);
		System.setProperty("weibo4j.oauth.consumerSecret", consumerSecret);
		weibo = new Weibo();
	}
	
	private boolean auth(String userId, String password) {
		boolean result = true;
		try {
	    	requestToken = weibo.getOAuthRequestToken();
	    	Parser parser = new Parser();
	    	String url = requestToken.getAuthorizationURL();
	    	parser.setURL(url);
			parser.setEncoding(parser.getEncoding());		
			NodeList nodeList = parser.parse(new NodeClassFilter(InputTag.class));		
			SimpleNodeIterator simpleNodeIterator = nodeList.elements();
			List<PostParameter> postParameterList = new ArrayList<PostParameter>();
			while (simpleNodeIterator.hasMoreNodes()) {
				Node node = simpleNodeIterator.nextNode();
				InputTag inputnode = (InputTag) node;
				String name = inputnode.getAttribute("name");
				String value = inputnode.getAttribute("value");
				if (name.equals("userId"))
					value = userId;
				else if (name.equals("passwd"))
					value = password;
				try {
					Validate.notNull(value);
					PostParameter pp = new PostParameter(name, value);
					postParameterList.add(pp);
				} catch (IllegalArgumentException e) {
				}			
			}		
			PostParameter[] postParameters = postParameterList.toArray(new PostParameter[0]);
			String response;
			
				response = requestToken.getHttpClient().post(url, postParameters).asString();
			
			Pattern pattern = Pattern.compile("<span class=\"fb\">.*</span>");
			Matcher matcher = pattern.matcher(response);
			String pin = "";
			while (matcher.find())
			{  
			   pin = response.substring(matcher.start(), matcher.end()).replace("<span class=\"fb\">", "").replace("</span>", "");
			   break;
			}
			try {
				Validate.notEmpty(pin);
				AccessToken accessToken = requestToken.getAccessToken(pin);
				token = accessToken.getToken();
				tokenSecret = accessToken.getTokenSecret();
				
			} catch (IllegalArgumentException e) {
				result = false;
			}
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				result = false;
		}
		return result;
	}

}
